from sys import *
import numpy as np
import os

fin=argv[1]
fout=argv[2]

line=int(os.popen("grep -n 'CELL_PARAMETER' %s | tail -n1"%fout).readlines()[0].split(":")[0])
alat=os.popen("sed -n %ip %s"%(line,fout)).readlines()[0].rstrip()
alat=float(alat[alat.index("=")+1:alat.index(")")])
latt=os.popen("sed -n '%i,%ip' %s"%(line+1,line+3,fout)).readlines()
Natom=os.popen("grep nat %s"%fin).readlines()[0].rstrip()
Natom=int(Natom[Natom.index("=")+1:Natom.index(",")])
line=int(os.popen("grep -n 'ATOMIC_POSITIONS' %s | tail -n1"%fout).readlines()[0].split(":")[0])
pos=os.popen("sed -n '%i,%ip' %s"%(line+1,line+Natom,fout)).readlines()

length=[]
for line in latt:
    line=line.rstrip().split()
    line=[float(i) for i in line]
    l=np.sqrt(sum([i**2 for i in line]))*0.5291777*alat
    length.append(l)

def reset(st,value,label,file='input'):
    N=int(os.popen("grep -n %s %s | tail -n1"%(st,file)).readlines()[0].split(":")[0])
    line="%s = %s,"%(label,value)
    os.system('sed -i %ic"%s" %s'%(N,line,file))

def getvalue(label,file='input'):
    line=os.popen("grep %s %s"%(label,file)).readlines()[0]
    return line[line.index("=")+1:line.index(',')].split()[0]

def note(label,file='input'):
    lines=os.popen("grep -n %s %s"%(label,file)).readlines()
    for line in lines:
        N=int(line.split(":")[0])
        aline=os.popen("sed -n %ip %s"%(N,file)).readlines()[0]
        os.system("sed -i %ic'!%s' %s"%(N,aline,file))

def denote(label,file='input'):
    lines=os.popen("grep -n %s %s"%(label,file)).readlines()
    for line in lines:
        N=int(line.split(":")[0])
        aline=os.popen("sed -n %ip %s"%(N,file)).readlines()[0]
        if aline[0]!="!":
            return
        else:
            os.system("sed -i %ic'%s' %s"%(N,aline[1:],file))

os.system("cp -f %s bkup"%fin)

reset("calculation","'scf'","calculation",fin)
reset("disk_io","'low'","disk_io",fin)
reset("len_a","%13.10f    !len_a"%length[0],'a',fin)
reset("len_b","%13.10f    !len_b"%length[1],'b',fin)
note("nstep",fin)
note("cell_dynamics",fin)
note("press",fin)
note("cell_dofree",fin)
denote("lda_plus_U",fin)
denote("U_projection_type",fin)
denote("Hubbard",fin)
lineN=int(os.popen("grep -n ATOMIC_POSITIONS %s"%fin).readlines()[0].split(":")[0])
for i in range(0,Natom):
    line=pos[i].rstrip()
    os.system("sed -i %ic'%s' %s"%(lineN+1+i,line,fin))
